package cn.buk.qms.service;

import cn.buk.tms.dao.FlightPolicyDao;
import cn.buk.tms.entity.misc.Enterprise;
import cn.buk.tms.entity.misc.ProductBought;
import cn.buk.common.util.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;


import static cn.buk.common.Constant.FUNCTION_UPLOAD_ALL_POLICY_PLAN_CTRIP;
import static cn.buk.common.Constant.SYSTEM_USERNAME;

/**
 *
 * @author yfdai
 */
public abstract class BaseFlightService extends  BaseAbstractService {

    private static final Logger logger = LogManager.getLogger(BaseFlightService.class);


    @Autowired
    FlightPolicyDao flightPolicyDao;

    @Autowired
    ProductService productService;

    int doCreateHistory(final int enterpriseId, final String username, final int functionId, final String remark) {
        return userDao.createHistory(enterpriseId, username, functionId, remark);
    }



    /**
     * 判断产品使用期限
     *
     * @param enterpriseId
     * @param productCode
     * @return 100: 可以正常使用
     * 1  : 余额不足
     */
    int isOverTimeLimit(final int enterpriseId, final String productCode) {
        int retCode = 0;
        Enterprise enterprise = userDao.getEnterpriseById(enterpriseId);
        if (enterprise == null) {
          return retCode;
        }


        //1. 检查付费购买的有效期是否已到
        ProductBought pb = productService.getProductBoughtByCode(enterpriseId, productCode);


        if (pb == null || DateUtil.getDaySpan(pb.getEndTime(), DateUtil.getCurDate()) < 0) {
            String prefixLog = enterpriseId + "," + productCode + ": ";
            //未购买,或者已过期需要重新购买
            //2.设定的监控政策数是多少, 按照其值进行计费
            retCode = productService.buyProduct(enterpriseId, productCode, 0, 1);
            if (retCode == 1) {
                //余额不足
                String remark = enterprise.getFullName() + "(" + enterpriseId + ")余额不足.";
                doCreateHistory(enterpriseId, SYSTEM_USERNAME, FUNCTION_UPLOAD_ALL_POLICY_PLAN_CTRIP, remark);
                logger.info(prefixLog + retCode + ", " + remark);
            } else {
                logger.info(prefixLog + retCode);
            }
        } else {
            retCode = 100;
            logger.info(enterpriseId + "," + pb.getProduct().getProductName() + "(" + productCode + "): " + pb.getEndTime());
        }

        return retCode;
    }

}
